package com.ejlchina.tool.adapter

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.ItemIndexFixBinding
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.network.BucketIndexInfo
import com.ejlchina.tool.util.LOG_TAG

class BucketIndexAdapter(private val dataList: List<BleDeviceBean>, private val bucketClick: (BleDeviceBean,beforeIndex :Int) -> Unit, private val indexClick: (Int) -> Unit): RecyclerView.Adapter<BucketIndexAdapter.BucketIndexViewHolder>() {

    private var selectIndex = -1
    var selectIndexBefore = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BucketIndexViewHolder {
        val binding = ItemIndexFixBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return BucketIndexViewHolder(binding,bucketClick)
    }

    override fun getItemCount(): Int {
        return  dataList.size
    }

    override fun onBindViewHolder(holder: BucketIndexViewHolder, position: Int) {
        holder.bindingData(dataList[position], position)
    }

    inner class BucketIndexViewHolder(private val binding: ItemIndexFixBinding ,private val bucketClick: (BleDeviceBean,beforeIndex :Int) -> Unit) :RecyclerView.ViewHolder(binding.root){
        @SuppressLint("SetTextI18n")
        fun bindingData(bucketIndexInfo: BleDeviceBean, position: Int){
            binding.tvMac.text = "MAC: ${bucketIndexInfo.bleDevice.mac}"
            binding.tvIndex.text = bucketIndexInfo.getBucketNoString()
            setItemBg(bucketIndexInfo,position)
            binding.root.setOnClickListener {
                selectIndexBefore = selectIndex

                selectIndex = if (selectIndex == position) -1 else position
                Log.i(LOG_TAG,"selectIndex--->$selectIndex ============selectIndexBefore--->$selectIndexBefore")
                bucketClick(bucketIndexInfo,selectIndex)
                notifyDataSetChanged()
            }
            binding.layoutIndex.setOnClickListener {
                indexClick(position)
                notifyDataSetChanged()
            }
        }

        private fun setItemBg(bucketIndexInfo: BleDeviceBean, position: Int){
            val resId = if (bucketIndexInfo.deviceNo.isEmpty()) {
                R.drawable.shape_co_8_st_ff3b30_so_f7f7f7
            } else {
                R.drawable.shape_co_8_so_f7f7f7
            }
            binding.layoutDevice.setBackgroundResource(resId)
            binding.layoutIndex.setBackgroundResource(resId)
            if (selectIndex == position){
                binding.layoutDevice.setBackgroundResource(R.drawable.shape_co_8_so_f7f7f7_st_1f39ff)
                binding.layoutIndex.setBackgroundResource(R.drawable.shape_co_8_so_f7f7f7_st_1f39ff)
            }
        }
    }
}